package com.tangyee.home_blood_center.activities;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.widget.Toast;

import com.tangyee.R;
import com.tangyee.home.activity.Login;
import com.tangyee.home.activity.db.UsersInfo;
import com.tangyee.home_blood_center.bean.BSRecord;
import com.tangyee.home_blood_center.db.BSRecordHolder;
import com.tangyee.home_blood_center.fragments.MainFragment;
import com.tangyee.home_blood_center.utils.DialogUtils;
import com.tangyee.home_blood_center.utils.HandleBackUtil;
import com.tangyee.utils.UserInfoUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Date;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends FragmentActivity {

    private Dialog mDialog;
    private UsersInfo mUsersInfo = UserInfoUtil.getLoadedUser();
    private String sessionid = mUsersInfo.getSessionid();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment);

        //禁止横屏，不禁止太多坑了
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        // 启动加载弹窗
        mDialog = DialogUtils.createLoadingDialog(MainActivity.this, "加载中...");

        new Loading().execute();
    }

    /**
     * 重写返回键点击方法，让其执行自定义的方法（将返回事件分发给所有继承了BaseFragment的fragment）
     */
    @Override
    public void onBackPressed() {
        if (!HandleBackUtil.handleBackPress(this)) {
            super.onBackPressed();
        }
    }

    private class Loading extends AsyncTask<Void, Void, String> {

        private static final String TAG = "MainActivity#Loading";

        @Override
        protected String doInBackground(Void... voids) {
            String r = null;
            OkHttpClient okHttpClient = new OkHttpClient();

            RequestBody body = new FormBody.Builder()
                    .add("rDay", "30")
                    .build();

            Request request = new Request.Builder()
                    .url("https://www.tangyee.com/Mobile/Health/GetBloodGlucose")
                    .addHeader("cookie", "ASP.NET_SessionId=" + sessionid)
                    .post(body)
                    .build();

            try {
                Response response = okHttpClient.newCall(request).execute();
                if (response.isSuccessful()) {
                    r = response.body().string();
                    JSONArray jsonArray = new JSONArray(r);
                    for(int i = 0; i < jsonArray.length(); i ++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        double dawn = jsonObject.getDouble("MBG");;
                        double beforeBreakfast = jsonObject.getDouble("BBFBG");;
                        double afterBreakfast = jsonObject.getDouble("ABFBG");;
                        double beforeLunch = jsonObject.getDouble("BLBG");
                        double afterLunch = jsonObject.getDouble("ALBG");;
                        double beforeDinner = jsonObject.getDouble("BDBG");;
                        double afterDinner = jsonObject.getDouble("ADBG");;
                        double beforeSleep = jsonObject.getDouble("BTBG");;
                        BSRecord bsRecord = new BSRecord();
                        bsRecord.setDataBySign(1, dawn);
                        bsRecord.setDataBySign(2, beforeBreakfast);
                        bsRecord.setDataBySign(3, afterBreakfast);
                        bsRecord.setDataBySign(4, beforeLunch);
                        bsRecord.setDataBySign(5, afterLunch);
                        bsRecord.setDataBySign(6, beforeDinner);
                        bsRecord.setDataBySign(7, afterDinner);
                        bsRecord.setDataBySign(8, beforeSleep);
                        String d = jsonObject.getString("RecordDate");
                        d = d.substring(6, d.length() - 2);
                        long dd = Long.parseLong(d);
                        Date date = new Date(dd);
                        Log.d(TAG, "doInBackground: " + date);
                        bsRecord.setDate(date);
                        BSRecordHolder.get(MainActivity.this).updateDate(bsRecord);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, "身份验证过期，请重新登陆！", Toast.LENGTH_SHORT).show();
                Intent i = new Intent(MainActivity.this, Login.class);
                startActivity(i);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            // 耗时操作都在这里
            FragmentManager fm = getSupportFragmentManager();
            Fragment fragment = fm.findFragmentById(R.id.fragment_container);
            if (fragment == null) {
                fragment = createFragment();
                // 允许状态值丢失 的 提交方式
                fm.beginTransaction().add(R.id.fragment_container, fragment).commitAllowingStateLoss();
            }

            return r;
        }

        @Override
        protected void onPostExecute(String s) {
            Log.d(TAG, s);
            DialogUtils.closeDialog(mDialog);
        }
    }

    protected Fragment createFragment() {/* 设置托管的Fragment为MainFragment*/
        return new MainFragment();
    }
}
